const app = getApp()
import { getCaseDetail, getCaseMore, postLikeCase, postMarkCase, getCommentList, addCaseComment, followSupplier } from '../../api/index'
import { formatTimeTwo, previewImg } from '../../utils/util'

Page({
  data: {
    type: '',
    id: '',
    caseSwiperIndex: 0,
    footerHeight: 0,
    detail: {
      caseDetailMore: [],
      caseDetailLinkMaterial: []
    },
    isCaseMore: 5,
    casePage: 2,
    casePageSize: 5,
    commentList: [],
    safeBottom: 0,
    commentValue: '',
    showAllComment: false,
    showCommentInput: false,
    currentItem: null,
    pageSize: 15,
    currentPage: 1,
    isEmpty: false,
    inputBottom: 0,
    showCommentMask: false,
    userInfo: {}
  },
  changeCaseSwiper ({ detail: { current } }) {
    this.setData({ caseSwiperIndex: current })
  },
  // async giveLike () {
  //   try {
  //     await postLikeCase({ materialCaseId: this.data.item.materialCaseId })
  //     this.data.item.likeFlag = !this.data.item.likeFlag
  //     if (this.data.item.likeFlag) {
  //       this.data.item.likeCount = this.data.item.likeCount + 1
  //     } else {
  //       this.data.item.likeCount = this.data.item.likeCount - 1
  //     }
  //     wx.showToast({ title: '操作成功！', icon: 'none' })
  //     this.setData({ 'item.likeFlag': this.data.item.likeFlag, 'item.likeCount': this.data.item.likeCount })
  //     this.triggerEvent('change', this.data.item)
  //   } catch (err) {
  //     wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
  //   }
  // },
  async giveLike ({ currentTarget: { dataset: { item, index } } }) {
    try {
      let query = {}
      if (item && item.materialCaseId) {
        query.materialCaseId = item.materialCaseId
      } else {
        query.materialCaseId = this.data.detail.materialCaseId
      }
      await postLikeCase({ ...query })
      if (item && item.materialCaseId) {
        item.likeFlag = !item.likeFlag
        if (item.likeFlag) {
          item.likeCount = item.likeCount + 1
        } else {
          item.likeCount = item.likeCount - 1
        }
        let key = `detail.caseDetailMore[${index}]`
        this.setData({
          [key]: item
        })
      } else {
        this.data.detail.likeFlag = !this.data.detail.likeFlag
        if (this.data.detail.likeFlag) {
          this.data.detail.likeCount = this.data.detail.likeCount + 1
        } else {
          this.data.detail.likeCount = this.data.detail.likeCount - 1
        }
        this.setData({
          'detail.likeFlag': this.data.detail.likeFlag,
          'detail.likeCount': this.data.detail.likeCount
        })
      }
      wx.showToast({ title: '点赞成功！', icon: 'none' })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async changeMark ({ currentTarget: { dataset: { item, index } } }) {
    try {
      let query = {}
      if (item && item.materialCaseId) {
        query.materialCaseId = item.materialCaseId
      } else {
        query.materialCaseId = this.data.detail.materialCaseId
      }
      await postMarkCase({ ...query })
      if (item && item.materialCaseId) {
        this.data.detail.caseDetailMore[index].markFlag = !this.data.detail.caseDetailMore[index].markFlag
        if (this.data.detail.caseDetailMore[index].markFlag) {
          this.data.detail.caseDetailMore[index].markCount = this.data.detail.caseDetailMore[index].markCount + 1
          wx.showToast({ title: '收藏成功！', icon: 'none' })
        } else {
          this.data.detail.caseDetailMore[index].markCount = this.data.detail.caseDetailMore[index].markCount - 1
          wx.showToast({ title: '取消收藏！', icon: 'none' })
        }
        let key = `detail.caseDetailMore[${index}]`
        this.setData({
          [key]: this.data.detail.caseDetailMore[index]
        })
      } else {
        this.data.detail.markFlag = !this.data.detail.markFlag
        if (this.data.detail.markFlag) {
          this.data.detail.markCount = this.data.detail.markCount + 1
          wx.showToast({ title: '收藏成功！', icon: 'none' })
        } else {
          this.data.detail.markCount = this.data.detail.markCount - 1
          wx.showToast({ title: '取消收藏！', icon: 'none' })
        }
        this.setData({
          'detail.markFlag': this.data.detail.markFlag,
          'detail.markCount': this.data.detail.markCount
        })
      }
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async collectionSupplier () {
    try {
      await followSupplier({ supplierId: this.data.detail.supplierId })
      this.data.detail.followFlag = !this.data.detail.followFlag
      wx.showToast({ title: '操作成功！', icon: 'none' })
      this.setData({ 'detail.followFlag': this.data.detail.followFlag })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  seeComment ({ currentTarget: { dataset: { id } } }) {
    let _this = this
    let query = wx.createSelectorQuery().in(this)
    query.selectViewport().scrollOffset()
    query.select("#" + id).boundingClientRect()
    query.exec(res => {
      let miss = res[0].scrollTop + res[1].top - 10
      wx.pageScrollTo({
        scrollTop: miss,
        duration: 300
      })
    })
  },
  seePreviewImg ({ currentTarget: { dataset: { item } } }) {
    previewImg(item, this.data.detail.fileUrlList)
  },
  changeInput ({ detail: { value } }) {
    this.setData({ commentValue: value })
  },
  seeCase ({ currentTarget: { dataset: { item } } }) {
    wx.$nav.navigateTo(`/pages/caseDetail/index?id=${item.materialCaseId}`)
  },
  async confirmComment () {
    try {
      await addCaseComment({ materialCaseId: this.data.detail.materialCaseId, commentContext: this.data.commentValue })
      wx.showToast({ title: '评论成功！', icon: 'none' })
      this.setData({ commentValue: '' })
      this.getCommentList()
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  keyboardheightchange ({ detail: { height, duration } }) {
    if (height) {
      this.data.inputBottom = this.data.safeBottom + 10
      this.setData({ inputBottom: this.data.inputBottom, showCommentMask: true })
    } else {
      this.setData({ inputBottom: this.data.safeBottom, showCommentMask: false })
    }
    // if (height <= 0 && duration > 0) {
    //   this.close()
    // }
  },
  closeCommentModal () {
    this.setData({ showCommentInput: false, inputBottom: this.data.safeBottom })
    this.getCommentList()
  },
  replyComment ({ detail }) {
    this.setData({
      showCommentInput: true,
      currentItem: detail,
      inputBottom: -100
    })
  },
  showAllCommentModal ({ currentTarget: { dataset: { item } } }) {
    this.setData({ showAllComment: true, currentItem: item })
    wx.setPageStyle({
      style: {
        overflow: 'hidden'
      }
    })
  },
  closeAllComment () {
    this.setData({ showAllComment: false, currentItem: null })
    wx.setPageStyle({
      style: {
        overflow: ''
      }
    })
  },
  async sendComment ({ detail }) {
    try {
      let query = {
        materialCaseId: this.data.detail.materialCaseId,
        commentContext: detail
      }
      if (this.data.currentItem) {
        query.parentId = this.data.currentItem.id
        query.topId = this.data.currentItem.id
      }
      await addCaseComment({...query})
      wx.showToast({ title: '评论成功！', icon: 'none' })
      this.setData({
        showCommentInput: false,
        currentComment: null
      })
      this.getCommentList()
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  onReachBottom () {
    this.loadCommentMore()
  },
  async loadCommentMore () {
    try {
      if (this.loading || this.alloaded) return
      this.loading = true
      let query = {
        materialCaseId: this.data.id,
        currentPage: this.data.currentPage,
        pageSize: this.data.pageSize
      }
      const { ResultSet } = await getCommentList({ ...query })
      this.alloaded = !ResultSet.userData.data.length
      this.data.isEmpty = !ResultSet.userData.data.length
      this.setData({ isEmpty: this.data.isEmpty })
      if (ResultSet.userData.data.length) {
        this.data.currentPage = this.data.currentPage + 1
        this.data.commentList.push(...ResultSet.userData.data)
        this.setData({
          commentList: this.data.commentList,
          currentPage: this.data.currentPage
        })
      }
      this.loading = false
    } catch (err) {
      this.loading = false
      console.log(err)
      wx.showToast({ title: err.message || err.ResultSet.errors })
    }
  },
  async getCommentList () {
    try {
      const { ResultSet } = await getCommentList({ materialCaseId: this.data.id, currentPage: 1, pageSize: 10 })
      this.data.isEmpty = ResultSet.userData.data.length && ResultSet.userData.data.length < this.data.pageSize
      ResultSet.userData.data.forEach(item => {
        item.commentTime = formatTimeTwo(item.commentTime * 1000, 'Y-M-D')
      })
      this.setData({
        currentPage: 2,
        isEmpty: this.data.isEmpty,
        commentList: ResultSet.userData.data
      })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async getDetail () {
    try {
      wx.showLoading({ title: '加载中...', mask: true })
      const { ResultSet } = await getCaseDetail({ materialCaseId: this.data.id })
      this.getCommentList()
      this.setData({
        detail: ResultSet.userData.data,
      })
      wx.hideLoading()
    } catch (err) {
      wx.hideLoading()
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async loadMoreCase () {
    try {
      const { ResultSet } = await getCaseMore({ materialCaseId: this.data.id, supplierId: this.data.detail.supplierId, currentPage: this.data.casePage, pageSize: this.data.casePageSize })
      this.data.detail.caseDetailMore.push(...ResultSet.userData.caseDetailMore)
      this.data.casePage += 1
      this.setData({
        'detail.caseDetailMore': this.data.detail.caseDetailMore,
        isCaseMore: this.data.casePage * this.data.casePageSize,
        casePage: this.daa.casePage
      })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
    
  },
  onLoad ({ type, id }) {
    let query = this.createSelectorQuery()
      query.select('.case-footer').boundingClientRect(rect=>{
        let height = rect.height
        this.setData({ footerHeight: height })
      }).exec()
    const { screenHeight, safeArea: { bottom } } = wx.$pro.getSystemInfoSync()
    const userInfo = app.globalData.userInfo ? app.globalData.userInfo : {}
    this.setData({ safeBottom: screenHeight - bottom, inputBottom: screenHeight - bottom, userInfo })
    let title = ''
    if (parseInt(type) === 1) {
      title ='视频详情'
    } else {
      title ='案例详情'
    }
    wx.setNavigationBarTitle({ title: title })
    this.setData({
      type: parseInt(type),
      id
    })
    this.getDetail()
  }
})